package cn.controller;

import cn.pojo.App_category;
import cn.pojo.App_info;
import cn.pojo.Data_dictionary;
import cn.pojo.Dev_user;
import cn.service.app_category.App_categoryService;
import cn.service.app_info.App_infoService;
import cn.service.data_dictionary.Data_dictionaryService;
import cn.tools.Constants;
import cn.tools.Page;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/app_info")
public class App_infoController {
    @Resource
    private App_infoService app_infoService;
    @Resource
    private Data_dictionaryService data_dictionaryService;
    @Resource
    private App_categoryService app_categoryService;

    private Logger log=Logger.getLogger(App_infoController.class);


    //分页条件查询所有
    @RequestMapping("/list")
    public String getAppInfoList(App_info app_info, Integer pageIndex, HttpSession session, HttpServletRequest request){
        log.info("======================");
        log.info("app_info.getSoftwareName()="+app_info.getSoftwareName());
        log.info("app_info.getAPKName()="+app_info.getAPKName());
        log.info("app_info.getCategoryLevel1()="+app_info.getCategoryLevel1());
        log.info("app_info.getCategoryLevel2()="+app_info.getCategoryLevel2());
        log.info("app_info.getCategoryLevel3()="+app_info.getCategoryLevel3());
        log.info("app_info.getFlatformId()="+app_info.getFlatformId());
        log.info("app_info.getDevId()="+app_info.getDevId());
        log.info("======================");
        if(pageIndex==null){
            pageIndex=1;
        }

        Page page=new Page();
        page.setPageIndex(pageIndex);
        page.setPageSize(5);
        page.setPageTotal(app_infoService.getAppInfoCount(app_info.getSoftwareName(),app_info.getStatus()
                            ,app_info.getCategoryLevel1(),app_info.getCategoryLevel2()
                            ,app_info.getCategoryLevel3(),app_info.getFlatformId(),app_info.getDevId()));
        log.info("page.pageIndex="+page.getPageIndex());
        log.info("page.pageSize="+page.getPageSize());
        log.info("page.pageTotal="+page.getPageTotal());
        log.info("page.pageCount="+page.getPageCount());
        List<App_info>list=app_infoService.getAppInfoList(app_info.getSoftwareName(),app_info.getStatus()
                ,app_info.getCategoryLevel1(),app_info.getCategoryLevel2()
                ,app_info.getCategoryLevel3(),app_info.getFlatformId(),app_info.getDevId()
                ,page.getPageIndex(),page.getPageSize());
        List<Data_dictionary>status=data_dictionaryService.getData_dictionaryStatus();//状态list集合
        List<Data_dictionary>flatform=data_dictionaryService.getData_dictionaryFlatfrom();//所属平台list集合
        //列出一级分类列表，注：二级三级分类类别通过ajax异步获取
        List<App_category>list1=app_categoryService.getApp_category1();
        request.setAttribute("list",list);
        request.setAttribute("page",page);
        request.setAttribute("app_info",app_info);
        request.setAttribute("status",status);
        session.setAttribute("flatform",flatform);
        request.setAttribute("list1",list1);
        return "dev_from";
    }

    //ajax分类获取一二三级分类
    @RequestMapping(value = "/categroyleve1",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public  String categroyleve1(Integer id){
        List<App_category> list = app_categoryService.getApp_category2(id);
        return JSONArray.toJSONString(list);
    }


    //ajax同时获取两级分类
    @RequestMapping(value = "/categroyleve23",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public  String categroyleve23(Integer id2,Integer id3){
        List<App_category> list2 = app_categoryService.getApp_category2(id2);
        List<App_category> list3 = app_categoryService.getApp_category2(id3);
        Map<String,List>map=new HashMap<>();
        map.put("list2",list2);
        map.put("list3",list3);
        return JSONArray.toJSONString(map);
    }

    //跳转到dev_add.jsp页面
    @RequestMapping("/dev_add.html")
    public String dev_addhtml(){
        return "dev_add";
    }

    //ajax异步查询
    @RequestMapping(value = "/checkAPKName",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String getAKPName(String AKPName){
        Map<String,Boolean>map=new HashMap<>();
        int num=app_infoService.apkName(AKPName);
        if(num>0){
            map.put("flag",true);
        }
        return JSONArray.toJSONString(map);
    }

    //添加APP基础信息
    @PostMapping("/add")
    public String  add(MultipartFile file,App_info app_info,HttpServletRequest request){
        app_info.setDevId( ((Dev_user)request.getSession().getAttribute(Constants.DEV_SESSION)).getId());
        app_info.setCreatedBy( ((Dev_user)request.getSession().getAttribute(Constants.DEV_SESSION)).getId());
        app_info.setCreationDate(new Date());
        app_info.setOnSaleDate(new Date());
        String filename="";
        if(!file.isEmpty()){
            String realPath = request.getSession().getServletContext().getRealPath("/upload");//获得tomcat系统路径
            File file1=new File(realPath);
            if(!file1.exists()){
                file1.mkdirs();
            }
            filename= file.getOriginalFilename();	//拿到文件名
            String suffx = FilenameUtils.getExtension(filename);		//获取原文件后缀
            int filesize=500000;
            if(file.getSize()>filesize){//上传大小不能超过500k
                request.setAttribute("fileUploadErro","上传大小不能超过500k");
                return "forward:/app_info/dev_add.html";
            }else if(suffx.equalsIgnoreCase("gif")||suffx.equalsIgnoreCase("jpg")||suffx.equalsIgnoreCase("png")){
                    filename = System.currentTimeMillis()+"."+suffx;	//修改文件名
                    File files=new File(realPath+"/"+filename);
                    app_info.setLogoLocPath(request.getContextPath()+"/upload/"+filename);
                    try {
                        file.transferTo(files);	//调用transferTo()方法上传文件
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    app_infoService.addApp_info(app_info);
                return "redirect:/app_info/list";
            }else{
                request.setAttribute("fileUploadErro","*上传文件格式不正确,要为(.gif,.jpg,.png)");
                return "forward:/app_info/dev_add.html";
            }
        }else{
            return "forward:/app_info/dev_add.html";
        }

    }

    //根据id获取信息
    @RequestMapping("/query")
    public  String query(int id,HttpServletRequest request){
        App_info app_info=app_infoService.getAPP_infoById(id);
        List<App_category> app_category1 = app_categoryService.getApp_category1();
        request.setAttribute("app_info",app_info);
        request.setAttribute("app_category1",app_category1);
        return "dev_change";
    }

    //根据id查看详情
    @RequestMapping("/view")
    public  String view(int id,HttpServletRequest request){
        App_info app_info=app_infoService.getAPP_infoById(id);
        request.setAttribute("app_info",app_info);
        return "dev_view";
    }
    //修改
    @RequestMapping("/update")
    public String  update(MultipartFile file,HttpServletRequest request) {
        String id = request.getParameter("id");
        String softwareSize = request.getParameter("softwareSize");
        String downloads = request.getParameter("downloads");
        String flatformId = request.getParameter("flatformId");
        String categoryLevel1 = request.getParameter("categoryLevel1");
        String categoryLevel2 = request.getParameter("categoryLevel2");
        String categoryLevel3 = request.getParameter("categoryLevel3");
        String status = request.getParameter("status");
        App_info app_info=new App_info();
        app_info.setModifyBy(((Dev_user) request.getSession().getAttribute(Constants.DEV_SESSION)).getId());
        app_info.setModifyDate(new Date());
        app_info.setId(Integer.parseInt(id));
        app_info.setSoftwareName(request.getParameter("softwareName"));
        app_info.setAPKName(request.getParameter("APKName"));
        app_info.setSupportROM(request.getParameter("supportROM"));
        app_info.setInterfaceLanguage(request.getParameter("interfaceLanguage"));
        app_info.setSoftwareSize(Integer.parseInt(softwareSize));
        app_info.setDownloads(Integer.parseInt(downloads));
        app_info.setFlatformId(Integer.parseInt(flatformId));
        app_info.setCategoryLevel1(Integer.parseInt(categoryLevel1));
        app_info.setCategoryLevel2(Integer.parseInt(categoryLevel2));
        app_info.setCategoryLevel3(Integer.parseInt(categoryLevel3));
        app_info.setStatus(Integer.parseInt(status));
        app_info.setAppInfo(request.getParameter("appInfo"));
        String filename = "";
        if (!file.isEmpty()) {
            String realPath = request.getSession().getServletContext().getRealPath("/upload");//获得tomcat系统路径
            File file1 = new File(realPath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            filename = file.getOriginalFilename();    //拿到文件名
            String suffx = FilenameUtils.getExtension(filename);        //获取原文件后缀
            int filesize = 500000;
            if (file.getSize() > filesize) {//上传大小不能超过500k
                request.setAttribute("fileUploadErro", "上传大小不能超过500k");
                return "forward:/app_info/query";
            } else if (suffx.equalsIgnoreCase("gif") || suffx.equalsIgnoreCase("jpg") || suffx.equalsIgnoreCase("png")) {
                filename = System.currentTimeMillis() + "." + suffx;    //修改文件名
                File files = new File(realPath + "/" + filename);
                app_info.setLogoLocPath(request.getContextPath() + "/upload/" + filename);
                try {
                    file.transferTo(files);    //调用transferTo()方法上传文件
                } catch (Exception e) {
                    e.printStackTrace();
                }
                app_infoService.change(app_info);
                return "redirect:/app_info/list";
            } else {
                request.setAttribute("fileUploadErro", "*上传文件格式不正确,要为(.gif,.jpg,.png)");
                return "forward:/app_info/query";
            }
        } else {
            return "forward:/app_info/query";
        }
    }

    //删除用户
    @RequestMapping("/del")
    public  String del(Integer id){
        app_infoService.del(id);
        return "redirect:/app_info/list";
    }





}
